//操作：用户增加和删除
package main

import (
	"crypto/md5"
	"encoding/hex"
	"log"
	"regexp"
	"strings"
	"time"

	"gopkg.in/pg.v5"
)

const adduser_sql = `insert into users(gid,uname,showname,pwd_md5,from_ip,reg_tm,login_tm) 
	values(?,?,?,?,?,?,NULL)`

func (self *Site) AddUser(gid int, name, shown, pwd, ip string) error {
	var db1 *pg.DB
	db1 = self.Db.Conn
	_, err := db1.Exec(adduser_sql, gid, name, shown, pwd, ip, time.Now())
	if err != nil {
		log.Println(err)
	}
	return err
}

const deluser_sql = "delete from users where uid=?"

func (self *Site) DelUser(uid int) error {
	var db1 *pg.DB
	db1 = self.Db.Conn
	_, err := db1.Exec(deluser_sql, uid)
	return err
}

type WUser struct {
	Uid      uint32
	Gid      uint32
	Uname    string
	Showname string
	Pwd_md5  string
}

const getuser_sql = "select uid,gid,uname,showname,pwd_md5 from users where uname=?;"

func HexMd5(s string) string {
	enc1 := md5.Sum([]byte(s))
	return hex.EncodeToString(enc1[:])
}
func (self *Site) VerifyUser(name, hexs, ip string) *WUser {
	var user1 *WUser = new(WUser)
	var db1 *pg.DB
	db1 = self.Db.Conn
	_, err := db1.Query(user1, getuser_sql, strings.Trim(name, " \t"))
	if err != nil {
		return nil
	}
	hex2 := HexMd5(ip + user1.Pwd_md5)
	if string(hex2) == hexs {
		return user1
	} else {
		return nil
	}
}

const userbyuid_sql = "select uid,gid,uname,showname,pwd_md5 from users where uid=?"

func (self *Site) VerifyUID(uid, hexs, ip string) *WUser {
	var user1 *WUser = new(WUser)
	var db1 *pg.DB
	db1 = self.Db.Conn
	r, err := db1.QueryOne(user1, userbyuid_sql, uid)
	if err != nil || r.RowsReturned() < 1 {
		return nil
	}
	hex2 := HexMd5(ip + user1.Pwd_md5)
	if string(hex2) == hexs {
		return user1
	} else {
		return nil
	}
}

const userbygid_sql = "select uid,gid,uname,showname,pwd_md5 from users where gid=?"

func (self *Site) GetUsersByGid(gid uint32) []WUser {
	var user1 []WUser
	var db1 *pg.DB
	db1 = self.Db.Conn
	_, err := db1.Query(&user1, userbygid_sql, gid)
	if err != nil {
		log.Println(err)
		return nil
	} else {
		return user1
	}
}

func GetIP(addr string) string {
	exp1, _ := regexp.CompilePOSIX(".*:")
	ip1 := exp1.FindString(addr)
	return ip1[0 : len(ip1)-1]
}

const updatepwd_sql = "update users set pwd_md5=? where uid=?"

func (self *Site) UpdatePass(uid int, pwd_md5 string) {
	db1 := self.Db.Conn
	_, err := db1.Exec(updatepwd_sql, pwd_md5, uid)
	if err != nil {
		log.Println(err)
	}
}

const updateshow_sql = "update users set showname=? where uid=?"

func (self *Site) UpdateShowname(uid int, name1 string) {
	db1 := self.Db.Conn
	_, err := db1.Exec(updateshow_sql, name1, uid)
	if err != nil {
		log.Println(err)
	}
}
